//
//  SeriesDetailViewController.m
//  ArandaTest
//
//  Created by Camilo Cadena on 2/18/15.
//  Copyright (c) 2015 Camilo Cadena. All rights reserved.
//

#import "SeriesDetailViewController.h"
#import "TvSeriesController.h"
#import "SeasonObject.h"
#import "SelectedSeasonController.h"
#import "UIImageView+AFNetworking.h"
#import "ServicesStrings.h"
#import "test1HeaderConstants.h"
#import "EpisodeTableViewCell.h"

@interface SeriesDetailViewController ()

@end

@implementation SeriesDetailViewController

- (void)viewDidLoad {
    //set active season, initialize seasons array and request service infromation with the selected season.
    self.seasonId = 0;
    self.mainArray = [[NSMutableArray alloc] initWithCapacity:self.seasonsArray.count];
    for(int i = 0; i < self.seasonsArray.count; i++) {
        [self.mainArray addObject:[NSNull null]];
    }
    //Update TV Show name
    [self updateShowName];
    
    
    //Get first season image path and request the image
    SeasonObject *seasonItem = [self.seasonsArray firstObject];
    [self loadImage:seasonItem];
    
    
    //Update scrollview with one button for each season
    [self updateScrollViewContent];
    
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillLayoutSubviews{
    float buttonWidth = 30;
    float buttonSpace = 5;
    
    //Updates container and ScrollView sizes
    CGRect containerFrame = self.containerView.frame;
    self.containerView.frame = CGRectMake(containerFrame.origin.x, containerFrame.origin.y, ((buttonWidth+buttonSpace)*self.seasonsArray.count) + buttonSpace, containerFrame.size.height);
    [self.seasonsScroll setContentSize:CGSizeMake(self.containerView.frame.size.width, self.containerView.frame.size.height)];
    NSLog(@"son %f",self.containerView.frame.size.width);
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
#pragma mark - Update UI Elements Methods
-(void)updateShowName{
    [self.tvTitle setText:[self.item.name uppercaseString]];
}

#pragma mark - UIScrollView

//Updates UIScrollView size and content
-(void)updateScrollViewContent{
    float index = 0;
    float buttonWidth = 30;
    float buttonSpace = 5;
    
    //Updates container and ScrollView sizes
    CGRect containerFrame = self.containerView.frame;
    self.containerView.frame = CGRectMake(containerFrame.origin.x, containerFrame.origin.y, ((buttonWidth+buttonSpace)*self.seasonsArray.count) + buttonSpace, containerFrame.size.height);
    [self.seasonsScroll setContentSize:CGSizeMake(self.containerView.frame.size.width, self.containerView.frame.size.height)];
    NSLog(@"son %f",self.containerView.frame.size.width);
    
    //Generates buttons for each season
    for(SeasonObject *season in self.seasonsArray){
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake((index*buttonWidth)+(buttonSpace * (index+1)), 6, buttonWidth, buttonWidth)];
        [button setTitle:[NSString stringWithFormat:@"%@",season.season_number] forState:UIControlStateNormal];
        button.tag = [season.season_number intValue];
        button.layer.cornerRadius = 4.0;
        button.backgroundColor = [UIColor colorWithRed:243/255.0 green:243/255.0 blue:243/255.0 alpha:1];
        [button setTitleColor:[UIColor colorWithRed:65/255.0 green:65/255.0 blue:65/255.0 alpha:1] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        [button addTarget:self action:@selector(selectedSeasonAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.containerView addSubview:button];
        
        if(index==0){
            button.selected = YES;
            button.backgroundColor = [UIColor colorWithRed:19/255.0 green:143/255.0 blue:179/255.0 alpha:1];
             [self requestEpisodesforSeason:[season.season_number intValue]];
        }

        index++;
    }
}



#pragma mark - IBActions
-(IBAction)selectedSeasonAction:(id)sender{
    UIButton *button = (UIButton *)sender;
    int activeButonTag = ((int)button.tag);
    
    
    //Clear buttons states
    for (int i = 0; i<self.containerView.subviews.count; i++) {
        if ([[self.containerView.subviews objectAtIndex:i] isKindOfClass:[UIButton class]]) {
            UIButton *button = (UIButton *)[self.containerView.subviews objectAtIndex:i];
            button.backgroundColor = [UIColor colorWithRed:243/255.0 green:243/255.0 blue:243/255.0 alpha:1];
            button.selected = NO;
        }
    }
    
    //Verifies if the selected button is different and if there is no previous dowloaded content
    if(self.seasonId != activeButonTag){
        button.selected = YES;
        button.backgroundColor = [UIColor colorWithRed:19/255.0 green:143/255.0 blue:179/255.0 alpha:1];
        self.seasonId = activeButonTag;
        NSArray *currentSeasonEpisodes = [self.mainArray objectAtIndex:self.seasonId];
        if(currentSeasonEpisodes == nil || [currentSeasonEpisodes isKindOfClass:[NSNull class]] || currentSeasonEpisodes.count<=0){
            [self requestEpisodesforSeason:activeButonTag];
        }else{
            [self.episodesTable setHidden:NO];
            [self.episodesTable reloadData];
        }
        
        //Get first season image path and request the image
        if(activeButonTag>=self.seasonsArray.count){
             [self loadImage:[self.seasonsArray lastObject]];
        }else{
            [self loadImage:[self.seasonsArray objectAtIndex:activeButonTag]];
        }
        [self hideNoResultView];
    }else{
        //reactivate button
        button.backgroundColor = [UIColor colorWithRed:19/255.0 green:143/255.0 blue:179/255.0 alpha:1];
        button.selected = YES;
        
        if(!self.noResultsView.isHidden){
            [self showNoResultView];
        }
    }
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *episodes = [self.mainArray objectAtIndex:self.seasonId];
    
    if([episodes isKindOfClass:[NSNull class]]){
        return 0;
    }else{
       return episodes.count;
    }
}

 - (UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
 {
     // Configure and update the Cell
     NSString *CellIdentifier = @"EpisodeTableViewCell";
     EpisodeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
     
     [cell updateCell:[[self.mainArray objectAtIndex:self.seasonId] objectAtIndex:indexPath.row]];
 
 return cell;
 }


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - Service Request
//Request episodes by season
-(void)requestEpisodesforSeason:(int)seasonIndex{
    [self.loaderEpisodes startAnimating];
    [self.view bringSubviewToFront:self.loaderEpisodes];
    
    
    SelectedSeasonController *controller = [[SelectedSeasonController alloc] init];
    [controller requestEpisodesForSeries:self.item.series_id season:[NSString stringWithFormat:@"%d",seasonIndex] andCompletionBlock:^(id response){
        if([response isKindOfClass:[NSArray class]]){
            
            [self.loaderEpisodes stopAnimating];
            NSArray *episodesArray = [[NSArray alloc] initWithArray:response];
            if(episodesArray.count>0){
                self.seasonId = seasonIndex;
                [self.episodesTable setHidden:NO];
                [self.mainArray insertObject:episodesArray atIndex:seasonIndex];
                [self.episodesTable reloadData];
                [self hideNoResultView];
            }else{
                [self.episodesTable setHidden:YES];
                
                [self.noResultsView setHidden:NO];
                self.noResultsView.alpha = 0;
                [UIView animateWithDuration:0.2 animations:^{
                    self.noResultsView.alpha = 1.0;
                }];
                //Season without episodes available
                [self showNoResultView];
            }
        }else{
            [self.loaderEpisodes stopAnimating];
            [self.episodesTable setHidden:YES];
            //Error in request, please check internet connection
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Please check your internet connection and try again!" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [alert show];
        }
    }];
    
}


//Load selected season image
-(void)loadImage:(SeasonObject *)seasonItem{
    
    //Vaidate if poster is available the the season
    if([seasonItem.poster_path isKindOfClass:[NSNull class]] || seasonItem.poster_path.length<=0 || seasonItem.poster_path == nil){
        //no image to load, put placeholder instead
        UIImage *placeholderImage = [UIImage imageNamed:@"placeholder"];
        self.tvSeasonImage.image = placeholderImage;
        self.tvSeasonImage.contentMode = UIViewContentModeCenter;
        return;
    }
    
    
    [self.loaderImage startAnimating];
    
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:KIMAGE_URL,seasonItem.poster_path]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    UIImage *placeholderImage = [UIImage imageNamed:@""];
    
    self.tvSeasonImage.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    [self.tvSeasonImage setClipsToBounds:YES];
    
    
    [self.tvSeasonImage setImageWithURLRequest:request placeholderImage:placeholderImage
                               success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
                                   self.tvSeasonImage.contentMode = UIViewContentModeScaleToFill;
                                   self.tvSeasonImage.image = image;
                                   [self.loaderImage stopAnimating];
                               } failure:nil];
    
}

#pragma mark - Noresultsview Animation Methods
//Hide and Show no result message when no episoded available for a selected season
-(void)showNoResultView{
    [self.noResultsView setHidden:NO];
    self.noResultsView.alpha = 0;
    [UIView animateWithDuration:0.2 animations:^{
        self.noResultsView.alpha = 1.0;
    }];
}

-(void)hideNoResultView{
    [self.noResultsView setHidden:YES];
    self.noResultsView.alpha = 0.0;
}

@end
